<template>
	<div class="standard-container layout-padding layout-pd">
		<!-- <el-card shadow="hover"> -->
		<div class="review-list-title">
			<div class="title-actions">
				<el-button size="default" type="primary" class="ml10" @click="handleBatchDeleteMenu">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					批量删除
				</el-button>
				<el-button size="default" type="primary" class="ml10" @click="onOpenAddMenu('add')">
					<el-icon>
						<ele-FolderAdd />
					</el-icon>
					{{ $t('message.sys.menu.add') }}
				</el-button>
			</div>
			<div class="title-actions">
				<el-button size="default" type="primary" class="ml10" @click="handleSearch">
					<el-icon>
						<ele-Search />
					</el-icon>
					{{ $t('message.common.search') }}
				</el-button>
			</div>
			<!-- <el-input size="default" placeholder="请输入菜单名称" style="max-width: 180px" clearable v-model="state.search.menuTitile"> </el-input> -->
		</div>
		<el-table
			:data="state.tableData.data"
			v-loading="state.tableData.loading"
			style="width: 100%"
			row-key="id"
			:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
			@selection-change="handleSelectionMenu"
		>
			<el-table-column type="selection" width="55" />
			<el-table-column label="菜单名称" show-overflow-tooltip>
				<template #default="scope">
					<SvgIcon :name="scope.row.meta.icon" />
					<span class="ml10">{{ $t(scope.row.menuTitle) }}</span>
				</template>
			</el-table-column>
			<el-table-column prop="path" label="路由地址" show-overflow-tooltip>
				<template #default="scope">
					<span>{{ scope.row.accessPath }}</span>
				</template>
			</el-table-column>
			<el-table-column label="组件路径" show-overflow-tooltip>
				<template #default="scope">
					<span>{{ scope.row.component }}</span>
				</template>
			</el-table-column>
			<!-- <el-table-column label="权限标识" show-overflow-tooltip>
					<template #default="scope">
						<span>{{ scope.row.meta.roles }}</span>
					</template>
				</el-table-column> -->
			<el-table-column label="排序" show-overflow-tooltip>
				<template #default="scope">
					{{ scope.row.menuSort }}
				</template>
			</el-table-column>
			<el-table-column label="是否外链" show-overflow-tooltip>
				<template #default="scope">
					<el-tag type="success" size="small" v-if="scope.row.meta.link"> 是</el-tag>
					<el-tag type="success" size="small" v-else>否</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" show-overflow-tooltip width="140">
				<template #default="scope">
					<el-button size="small" text type="primary" @click="onOpenAddMenu('add', scope.row)">新增</el-button>
					<el-button size="small" text type="primary" @click="onOpenEditMenu('edit', scope.row)">修改</el-button>
					<el-button size="small" text type="primary" @click="onTabelRowDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- </el-card> -->
		<MenuDialog ref="menuDialogRef" @refresh="getTableData()" />
	</div>
</template>

<script setup lang="ts" name="systemMenu">
import { defineAsyncComponent, ref, onMounted, reactive } from 'vue';
import { RouteRecordRaw } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useRoutesList } from '/@/stores/routesList';
import { useMenuApi } from '/@/api/sys/menu';
import msg from '/@/utils/messageUtils';

// 引入组件
const MenuDialog = defineAsyncComponent(() => import('/@/views/system/menu/dialog.vue'));
const meneApi = useMenuApi();
// 定义变量内容
const stores = useRoutesList();
const { routesList } = storeToRefs(stores);
const menuDialogRef = ref();
const state = reactive({
	tableData: {
		data: [] as RouteRecordRaw[],
		loading: true,
	},
	search: {
		menuTitile: '',
	},
	choiceIds: [],
});

const handleSelectionMenu = (menus: any) => {
	state.choiceIds = [];
	menus.forEach((u: any) => {
		state.choiceIds.push(u.id);
	});
};

const handleBatchDeleteMenu = () => {
	console.log('userIds: ', JSON.stringify(state.choiceIds));
	if (state.choiceIds.length < 1) {
		msg().warn('请至少选中一个菜单');
		return;
	}
	ElMessageBox.confirm(`此操作将永久选中的菜单，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			try {
				await useMenuApi().batchDelete({
					menuIds: state.choiceIds,
				});
				getTableData();
				msg().success('批量删除成功');
			} catch (error) {
				msg().error('批量删除失败');
			}
		})
		.catch(() => {});
};

const handleSearch = async () => {
	if (!state.search.menuTitile) {
		getTableData();
		return;
	}

	state.tableData.loading = true;
	try {
		const { data } = await meneApi.getSearchMenus({
			menuTitle: state.search.menuTitile,
		});
		state.tableData.data = data;
	} catch (error) {
		msg().error('请求失败，请重试');
	}
	state.tableData.loading = false;
};

// const getTableData = () => {
// 	state.tableData.loading = true;
// 	state.tableData.data = routesList.value;
// 	setTimeout(() => {
// 		state.tableData.loading = false;
// 	}, 500);
// };
// 获取路由数据，真实请从接口获取
const getTableData = async () => {
	state.tableData.loading = true;
	try {
		const { data } = await meneApi.getTreeMenus();
		// console.log(JSON.stringify(data));
		state.tableData.data = data;
		if (!data) {
			// 这里要把根目录带上
			// const root = [{ id: '0', menuName: 'root', meta: { title: 'root' }, children: [] }];
			// root[0].children.push(data);
			// console.log('root: ', JSON.stringify(root));
			const realTimeRouteList = Array.prototype.concat([{ id: '0', menuName: '根菜单', meta: { title: '根菜单' } }], data);
			stores.setRealTimeRouteList(realTimeRouteList);
			// stores.setRealTimeRouteList(root);
		} else {
			const root = [{ id: '0', menuName: '根菜单', meta: { title: '根菜单' }, children: [] }];
			// Array.prototype.concat(root[0].children, data);
			root[0].children = data;
			stores.setRealTimeRouteList(root);
			// console.log('root: ', JSON.stringify(root));
			// console.log('root: ', JSON.stringify(data));
			// stores.setRealTimeRouteList(root);
		}
		// 设置到本地数据里面
		//
		//
	} catch (error) {
		msg().error('请求失败，请重试');
	}
	state.tableData.loading = false;
};

// 打开新增菜单弹窗
const onOpenAddMenu = (type: string, row?: any) => {
	menuDialogRef.value.openDialog(type, row);
};
// 打开编辑菜单弹窗
const onOpenEditMenu = (type: string, row: RouteRecordRaw) => {
	menuDialogRef.value.openDialog(type, row);
};
// 删除当前行
const onTabelRowDel = (row: any) => {
	ElMessageBox.confirm(`此操作将永久删除路由：${row.menuTitle}, 是否继续?`, '提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			const id = row.id;
			await meneApi.deleteMenu(id);
			// console.log('id: ', id);
			ElMessage.success('删除成功');
			getTableData();
			//await setBackEndControlRefreshRoutes() // 刷新菜单，未进行后端接口测试
		})
		.catch(() => {
			ElMessage.error('删除失败');
		});
};
// 页面加载时
onMounted(() => {
	getTableData();
});
</script>
